package io.zt.dangyuan;

import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.ex.HttpException;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Calendar;
import java.util.HashMap;

import io.zt.dangyuan.object.UserModel;
import io.zt.dangyuan.util.Cons;

import com.bumptech.glide.Glide;
/**
 * Created by Administrator on 2015/11/10.
 */
public class PersonalActivity extends BaseActivity {
    public static final int PHOTOZOOM = 0; // 相册/拍照
    public static final int PHOTOTAKE = 1; // 相册/拍照
    public static final int IMAGE_COMPLETE = 2; // 结果
    private String photoSavePath;//保存路径
    private String photoSaveName;//图pian名
    private String path="";//图片全路径
    private AlertDialog.Builder builder;
    private de.hdodenhof.circleimageview.CircleImageView CircleImageView;
    private int userid;
    private Button button;
    private EditText  ev_name, ev_address, ev_phone, ev_tel, ev_email, ev_wenxin, ev_unit, ev_post;
    private RadioButton radioButton_yes, radioButton_no;
    private RadioGroup radioGroup;
    private TextView tv_birthday1;
    private ToggleButton mTogBtn;
    private String tel;
    private String phone;
    String single;//是否单身
    String sex;//男女
    File file;
    boolean radio;
    private String headUrl;
    String url = "updateUser.json?userid=";
    String url1="groupInfo.json?userid=";
    private String headUrl1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_people_info_personal);
        initView();
        final GlobalDataApplication app = (GlobalDataApplication) getApplication();
        userid = app.getUserModel().getUserid();
        // initData();
        validate();
        //bindEvets();
        loadHead(app);
        getinfo();



    }//判断男女
    public void sex() {
        if (mTogBtn.getText().toString().equals("男")){
            sex="1";
        }else if (mTogBtn.getText().toString().equals("女")){
            sex="0";
        }

    }

    public void loadHead(GlobalDataApplication app) {
        if (app != null) {
            Glide.with(this).load(Cons.BASE_URL + app.getUserModel().getUserimg()).placeholder(R.drawable.ic_laucher).into(CircleImageView);
        }

    }

    public void initView() {
        CircleImageView = (de.hdodenhof.circleimageview.CircleImageView) findViewById(R.id.people_head);
        button = (Button) findViewById(R.id.button2);
        mTogBtn = (ToggleButton) findViewById(R.id.mTogBtn);
        ev_name = (EditText) findViewById(R.id.ev_name);
        ev_address = (EditText) findViewById(R.id.ev_address);
        ev_phone = (EditText) findViewById(R.id.ev_phone);
        ev_tel = (EditText) findViewById(R.id.ev_tel);
        ev_email = (EditText) findViewById(R.id.ev_email);
        ev_wenxin = (EditText) findViewById(R.id.ev_wenxin);
        tv_birthday1=(TextView)findViewById(R.id.tv_birthday1);
        ev_unit = (EditText) findViewById(R.id.ev_unit);
        ev_post = (EditText) findViewById(R.id.ev_post);
        tv_birthday1.setInputType(InputType.TYPE_NULL);
        radioGroup=(RadioGroup)findViewById(R.id.radioGroup);
        //tv_sex1=(TextView)findViewById(R.id.tv_sex1);
        radioButton_yes= (RadioButton) findViewById(R.id.radioButton_yes);
        radioButton_no = (RadioButton) findViewById(R.id.radioButton_no);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == radioButton_yes.getId()) {
                    single = "1";
                    radio = false;
                }
                if (checkedId == radioButton_no.getId()) {
                    single = "0";
                    radio = true;
                } else {
                    radio = true;
                }

            }
        });

        /*tv_sex1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                choosesex();
            }
        });*/

        //日期选择
        tv_birthday1.setOnFocusChangeListener(new View.OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                // TODO Auto-generated method stub
                if (hasFocus) {
                    Calendar c = Calendar.getInstance();
                    new DatePickerDialog(PersonalActivity.this, new DatePickerDialog.OnDateSetListener() {

                        @Override
                        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                            // TODO Auto-generated method stub
                            tv_birthday1.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
                        }
                    }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH)).show();

                }
            }
        });

        tv_birthday1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Calendar c = Calendar.getInstance();
                new DatePickerDialog(PersonalActivity.this, new DatePickerDialog.OnDateSetListener() {

                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        // TODO Auto-generated method stub
                        tv_birthday1.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
                    }
                }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH)).show();

            }
        });
        //ToggleButton
        mTogBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mTogBtn.isChecked()){
                    mTogBtn.setText("女");
                }else {
                    mTogBtn.setText("男");
                }
            }
        });
    }
//选择性别
/*private void choosesex(){
    AlertDialog.Builder builder = new AlertDialog.Builder(PersonalActivity.this);
    builder.setTitle("选择性别");
    //    指定下拉列表的显示数据
    final String[] cities = {"男", "女"};
    //    设置一个下拉的列表选择项
    builder.setItems(cities, new DialogInterface.OnClickListener()
    {
        @Override
        public void onClick(DialogInterface dialog, int which)
        {
           // Toast.makeText(PersonalActivity.this, "选择性别为：" + cities[which], Toast.LENGTH_SHORT).show();
            tv_sex1.setText(cities[which]);
        }
    });
    builder.show();
}*/
    /*private void initData(){
        ev_name.setText(GlobalDataApplication.userModel.getRealname());
        ev_dob.setText(GlobalDataApplication.userModel.getRealname());
        ev_address.setText(GlobalDataApplication.userModel.getRealname());
        ev_phone.setText(GlobalDataApplication.userModel.getRealname());
        ev_tel.setText(GlobalDataApplication.userModel.getRealname());
        ev_email.setText(GlobalDataApplication.userModel.getRealname());
        ev_wenxin.setText(GlobalDataApplication.userModel.getRealname());
    }*/


    public void bindEvets() {
        Log.e("add","2222");

        //提交信息
        /*button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {*/

//                RealInfoEntity entity=new RealInfoEntity();
//                  final ProgressDialog dialog = new ProgressDialog(PersonalActivity.this);
//                dialog.setMessage("正在上传信息...");
//                dialog.show();

        HashMap<String,Object> params = new HashMap<String,Object>();
        params.put("userid", String.valueOf(userid));

        if (path == null||path.equals("") ) {
Log.e("aaaa",".......");
            params.put("uploadFile","");
            url = "updateUser1.json?userid=";
        }else{
            params.put("uploadFile", new File(path));
        }

        params.put("realname", ev_name.getText().toString());
                Log.e("tag......", mTogBtn.getText().toString());
        Log.e("tag......", tv_birthday1.getText().toString().trim());
        Log.e("tag......", single);
        sex();
                params.put("sex", sex);
                params.put("birthday", tv_birthday1.getText().toString());
            params.put("address", ev_address.getText().toString());
                params.put("mobile", ev_phone.getText().toString());
            params.put("email", ev_email.getText().toString());
        params.put("phone", ev_tel.getText().toString());
            params.put("weixin", ev_wenxin.getText().toString());
                params.put("single", single);
        WebUtils.sendPost(PersonalActivity.this, url+userid, params, new WebUtils.OnWebListenr() {

            @Override
            public void onSuccess(boolean isSuccess, String msg, String data) {
                String result1 = data;
                try {
                    JSONObject json1 = new JSONObject(result1);
                    if (json1.getString("success").equals("true")) {
                        Toast.makeText(PersonalActivity.this, "上传成功", Toast.LENGTH_LONG).show();
                        Log.e("tag", "上传成功");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailed(HttpException error, String msg) {
                Toast.makeText(PersonalActivity.this, "上传失败" + msg, Toast.LENGTH_LONG).show();
            }
                });
                finish();
       /*     }
        });
*/
    }

    public void onClick(View view) {
        finish();
    }

    /*String str1="";
    EditText editText1 =(EditText)findViewById(R.id.editText1);
    str1=editText1.getText().toString();*/
    public void people_head2(View view) {
        File file = new File(Environment.getExternalStorageDirectory(), "ClipHeadPhoto/cache");
        if (!file.exists())
            file.mkdirs();
        photoSavePath = Environment.getExternalStorageDirectory() + "/ClipHeadPhoto/cache/";
        String[] items = new String[]{"拍照", "从手机中选择"};
        // 实例化对话框
        builder = new AlertDialog.Builder(this);
        // 设置对话框标题
        builder.setTitle("选择图片");
        //
        builder.setIcon(android.R.drawable.ic_menu_more);
        // 简单的列表项对话框
        builder.setItems(items, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int id) {
                switch (id) {
                    case 0:
                        doTakePhoto();
                        break;
                    case 1:
                        doSelectImageFromLoacal();
                        break;
                }
                // 关闭对话框
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int id) {
                dialog.dismiss();
            }
        });
        builder.show();
    }


    /**
     * 拍照获取图片
     */
    public void doTakePhoto() {
        photoSaveName = String.valueOf(System.currentTimeMillis()) + ".png";
        Uri imageUri = null;
        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        imageUri = Uri.fromFile(new File(photoSavePath, photoSaveName));
        openCameraIntent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
        openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(openCameraIntent, PHOTOTAKE);

    }

    /**
     * 从相册中选择
     */
    public void doSelectImageFromLoacal() {
        Intent openAlbumIntent = new Intent(Intent.ACTION_GET_CONTENT);
        openAlbumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(openAlbumIntent, PHOTOZOOM);
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        Uri uri = null;
        switch (requestCode) {
            case PHOTOZOOM://相册
                if (data == null) {
                    return;
                }
                uri = data.getData();
                if (DocumentsContract.isDocumentUri(this, uri)) {
                    String wholeID = DocumentsContract.getDocumentId(uri);
                    String id = wholeID.split(":")[1];
                    String[] column = {MediaStore.Images.Media.DATA};
                    String sel = MediaStore.Images.Media._ID + "=?";
                    Cursor cursor = getContentResolver().query(
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, column, sel,
                            new String[]{id}, null);
                    int columnIndex = cursor.getColumnIndex(column[0]);
                    if (cursor.moveToFirst()) {
                        path = cursor.getString(columnIndex);
                    }
                    cursor.close();
                } else {
                    String[] projection = {MediaStore.Images.Media.DATA};
                    Cursor cursor = getContentResolver().query(uri,
                            projection, null, null, null);
                    int column_index = cursor
                            .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    cursor.moveToFirst();
                    path = cursor.getString(column_index);
                }
                Intent intent3 = new Intent(this, ClipActivity.class);
                intent3.putExtra("path", path);
                startActivityForResult(intent3, IMAGE_COMPLETE);
                break;
            case PHOTOTAKE://拍照
                path = photoSavePath + photoSaveName;
                uri = Uri.fromFile(new File(path));
                Intent intent2 = new Intent(this, ClipActivity.class);
                intent2.putExtra("path", path);
                startActivityForResult(intent2, IMAGE_COMPLETE);
                break;
            case IMAGE_COMPLETE:
                path = data.getStringExtra("path");
                CircleImageView.setImageBitmap(getLoacalBitmap(path));
//                upload(path);
                break;
            default:
                break;
        }
    }

    /**
     * 上传头像
     *
     * @param path
     */
    private void upload(final String path) {
        String url = "uploadUserImg.json";
        //携带的数据
        HashMap<String,Object> params = new HashMap<String,Object>();
        params.put("userid", String.valueOf(userid));
        params.put("uploadFile", new File(path));
        WebUtils.sendPost(PersonalActivity.this, url, params, new WebUtils.OnWebListenr() {
            @Override
            public void onSuccess(boolean isSuccess, String msg, String data) {
                String result = data;
                String uri = "";
                try {
                    JSONObject json = new JSONObject(result);
                    uri = json.getString("message");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                UserModel model = ((GlobalDataApplication) getApplication()).getUserModel();
                model.setUserimg(uri);
                ((GlobalDataApplication) getApplication()).setUserModel(model);
                CircleImageView.setImageBitmap(getLoacalBitmap(path));
            }

            @Override
            public void onFailed(HttpException error, String msg) {
                Toast.makeText(PersonalActivity.this, "上传失败" + msg, Toast.LENGTH_LONG).show();
            }
        });
    }

    /**
     * @param url
     * @return
     */
    public static Bitmap getLoacalBitmap(String url) {
        try {
            FileInputStream fis = new FileInputStream(url);
            return BitmapFactory.decodeStream(fis);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    //判断个人信息中必填的有没有写完整
    private void validate() {

        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Log.e("add", "4444444");
                mTogBtn.setText("男");
                if (ev_name.getText().toString().equals("")
                        | tv_birthday1.getText().toString().equals("")
                        | ev_phone.getText().toString().equals("")
                        | (radio == false)
                        ) {

                    Toast.makeText(PersonalActivity.this, "必填的没有填写", Toast.LENGTH_LONG).show();
                }
                /*if (mTogBtn.getText().toString().equals("")){
                    mTogBtn.setText("男");
                    Log.e("add", "444444441111");
                }*/
                else {
                    Log.e("add", "4444444222");
                    dialog();
                    Log.e("add", "1111");
                }

            }
        });



    }
    //从网上获取获取单位和职务的信息
    private void getinfo(){
        WebUtils.sendPost(PersonalActivity.this, url1+userid ,new HashMap<String,Object>(), new WebUtils.OnWebListenr() {
            @Override
            public void onSuccess(boolean isSuccess, String msg, String data) {
                String result = data;
                try {
                    org.json.JSONObject object = new org.json.JSONObject(result);
                    org.json.JSONObject json = object.getJSONObject("data");
                    String single = json.getString("single");
                    if (single.equals("1")) {
                        radioGroup.check(R.id.radioButton_yes);
                    } else if(single.equals("0")){
                        radioGroup.check(R.id.radioButton_no);
                    }
                    String sex=json.getString("sex");
                    ev_name.setText(json.getString("realname"));
                    headUrl1 = json.getString("userimg");
                    ev_unit.setText(json.getString("workunit"));
                    ev_post.setText(json.getString("position"));
                    tv_birthday1.setText(json.getString("birthday"));
                    ev_address.setText(json.getString("address"));
                    phone = json.getString("mobile");
                    ev_phone.setText(phone);
                    ev_email.setText(json.getString("email"));
                    tel = json.getString("phone");
                    ev_tel.setText(tel);
                    ev_wenxin.setText(json.getString("weixin"));

                    Log.e("tag........", headUrl1);
                    //pd.dismiss();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailed(HttpException error, String msg) {
                Toast.makeText(PersonalActivity.this, "数据请求失败" + msg, Toast.LENGTH_LONG).show();
            }
        });
    }
    //对话框
    protected void dialog() {
        //AlertDialog.Builder normalDialog=new AlertDialog.Builder(getApplicationContext());
        AlertDialog.Builder normalDia=new AlertDialog.Builder(PersonalActivity.this);
        normalDia.setTitle("保存对话框");
        normalDia.setMessage("信息填写完毕，确认保存？");

        normalDia.setPositiveButton("保存", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                Log.e("add","33333");
                bindEvets();
                finish();
            }
        });
        normalDia.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                dialog.dismiss();
            }
        });
        normalDia.create().show();
    }
    //获取单位和职务的信息
}
